package syncMembers

import (
	"sieve_admin_server_userpass/pkg/config"
	"sieve_admin_server_userpass/pkg/im3/app/api"
	"sieve_admin_server_userpass/pkg/im3/app/server"
	"sieve_admin_server_userpass/pkg/log"
)

var (
	syncDept = config.Bool("server.syncDept", false, "sync dept data")
)

func init() {
	server.AfterDbOpen(func() {
		server.DB().Exec("CREATE TABLE IF NOT EXISTS `im_allUser` (`Uid` int(11) NOT NULL,`Name` varchar(255) NOT NULL,`Email` varchar(255) NOT NULL,`Dept` int(11) NOT NULL,UNIQUE KEY `uid` (`Uid`),KEY `dept` (`Dept`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;")

		server.DB().Exec("CREATE TABLE IF NOT EXISTS  `im_dept` (`Did` int(10) NOT NULL,`Name` varchar(255) NOT NULL,`Leader` int(10) NOT NULL,KEY `Did` (`Did`),KEY `Leader` (`Leader`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;")
	})
	// server.OnSyncUsers(UpdateImUserFunc)
}

func UpdateImUser(userList []*api.Member) {
	tx, err := server.DB().Begin()
	if err != nil {
		log.Err(err)
		return
	}
	if _, err := tx.Exec("delete from im_allUser"); err != nil {
		log.Err(err)
		tx.Rollback()
		return
	}
	// stmt, err := tx.Prepare("INSERT INTO im_allUser(Uid,Name,Email,Dept) VALUES(?,?,?,?)")
	// if err != nil {
	//	log.Err(err)
	//	tx.Rollback()
	// }
	for _, info := range userList {
		if _, err := tx.Exec("INSERT INTO im_allUser(Uid,Name,Email,Dept) VALUES(?,?,?,?)", info.Uid, info.Name, info.Email, info.Dept); err != nil {
			log.Err(err)
			tx.Rollback()
			return
		}
	}
	err = tx.Commit()
	if err != nil {
		log.Err(err)
	}
}

func UpdateImDept(deptList []*api.Dept) {
	tx, err := server.DB().Begin()
	if err != nil {
		return
	}
	if _, err := tx.Exec("delete from im_dept"); err != nil {
		tx.Rollback()
		return
	}
	for _, info := range deptList {
		if _, err := tx.Exec("INSERT INTO im_dept(Did,Name,Leader) VALUES(?,?,?)", info.Did, info.Name, info.Leader); err != nil {
			tx.Rollback()
			return
		}
	}
	tx.Commit()
}
func UpdateImUserFunc() {
	list, err := api.GetAllMembers()
	if err != nil {
		return
	}
	UpdateImUser(list)

	if *syncDept {
		list, err := api.GetDepts()
		if err != nil {
			return
		}
		UpdateImDept(list)
	}
}
